import PropTypes from 'prop-types';
import { useParams } from 'react-router-dom';
import { itemImages } from '../items';
import './DetailItem.css';
import { CartTypes } from '../reducers/cartReducer';
import ItemType from '../types/item';

function DetailItem({ items, dispatch }) {
  const { id } = useParams();
  const detailItem = items.find((item) => item.itemId === id);
  const addItemToCart = () => {
    dispatch({ type: CartTypes.ADD, itemId: detailItem.itemId });
  };
  return (
    <div className="detail-item-component">
      {detailItem
        ? (
          <>
            <img
              src={itemImages[detailItem.itemId]}
              alt={detailItem.title}
              className="details-image"
            />
            <h2>{detailItem.title}</h2>
            <div>
              $
              {(detailItem.salePrice ?? detailItem.price).toFixed(2)}
            </div>
            {detailItem.description && <h6>{detailItem.description}</h6>}
            <button type="button" onClick={addItemToCart}>Add to Cart</button>
          </>
        )
        : <div>Unknown Item</div>}
    </div>
  );
}

DetailItem.propTypes = {
  items: PropTypes.arrayOf(ItemType).isRequired,
  dispatch: PropTypes.func.isRequired,
};

export default DetailItem;
